# -*- coding: utf-8 -*-
"""
@author: chenkang
@contact: QQ:1638245306
@Created on: 2021/6/3 003 0:30
@Remark: 用户管理
"""
from django.contrib.auth.hashers import make_password
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from system.user.models import Users
from utils.json_response import SuccessResponse, ErrorResponse
from utils.viewset import CustomModelViewSet
from system.user.serializers import UserSerializer, UserCreateSerializer, UserUpdateSerializer, UserInfoSerializer
from rest_framework.response import Response


@api_view(['GET'])
@permission_classes((IsAuthenticated,))
def user_info(request):
    """获取当前用户信息"""
    serializer_user = UserInfoSerializer(request.user)
    data = {
        "code": 200,
        "data": serializer_user.data,
        "message": "",
        "success": True,

    }
    return Response(data=data)


from django.shortcuts import HttpResponse
from utils.sign import SignAuthentication


@SignAuthentication
def test_api(request):
    print("1111")
    return HttpResponse("2222222222222")


class UserViewSet(CustomModelViewSet):
    """
    用户接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Users.objects.all()
    serializer_class = UserSerializer
    create_serializer_class = UserCreateSerializer
    update_serializer_class = UserUpdateSerializer

    def change_password(self, request, *args, **kwargs):
        """密码修改"""
        # instance = Users.objects.filter(id=kwargs.get('pk')).first()
        instance = request.user
        data = request.data
        old_pwd = data.get('old_password')
        new_pwd = data.get('new_password')
        new_pwd2 = data.get('confirm')
        if instance:
            if new_pwd != new_pwd2:
                return ErrorResponse(message="两次密码不匹配")
            elif instance.check_password(old_pwd):
                instance.password = make_password(new_pwd)
                instance.save()
                return SuccessResponse(data=None, message="修改成功")
            else:
                return ErrorResponse(message="旧密码不正确")
        else:
            return ErrorResponse(message="未获取到用户")
